﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data.SqlClient;
using System.Data;

namespace ConsoleApplication
{
    public class SplitUser
    {
        public static void SplitUserInfo()
        {
            List<string> ListAvailable = new List<string>();
            List<string> ListUnAvailable = new List<string>();
            StreamReader sr = new StreamReader(@"C:\Users\Jiangzm\Desktop\ListString4.txt", Encoding.UTF8);//必须要指定编码格式，否则中文会乱码，应该可以用UTF-8
            while (sr.Peek() > -1)
            {
                string ReadString = sr.ReadLine().Trim();
                if (ReadString == String.Empty) continue;
                if (!ReadString.Contains(" ")) continue;
                string StartString = ReadString.Substring(0, ReadString.IndexOf(' '));
                string EndString = ReadString.Substring(ReadString.LastIndexOf(' ') + 1);
                string MiddleString = ReadString.Remove(ReadString.LastIndexOf(' ') + 1, EndString.Length);
                MiddleString = MiddleString.Remove(0, StartString.Length);
                if (MiddleString.Trim() == String.Empty)
                {

                }
                else
                {
                    if (!EndString.Contains('@') || !EndString.Contains('.'))
                    {
                    }
                }
            }
        }

        public static void CreateTableTianya_User()
        {
            #region Tianya_User
            string connectionString = "server=.;database=UserDatabase;uid=sa;pwd=123456;Max Pool Size = 512;";
            DateTime time = DateTime.Now;
            SqlBulkCopy sqlBC = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction);
            sqlBC.DestinationTableName = "Tianya_User";
            DataTable dt = new DataTable("Tianya_User");
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("UserName", typeof(string));
            dt.Columns.Add("PassWord", typeof(string));
            dt.Columns.Add("Email", typeof(string));
            DirectoryInfo direct = new DirectoryInfo(@"E:\Jiangzm\WebsiteData\tianya");
            string[] userInfo;
            string readStr;
            int totalNum = 0;
            int partNum = 0;
            int totalError = 0;
            int partError = 0;
            foreach (FileInfo NextFile in direct.GetFiles())
            {
                partNum = 0;
                partError = 0;
                List<string> list4 = new List<string>();
                Console.WriteLine("正在读取文件：" + NextFile.FullName);
                StreamReader sr = new StreamReader(NextFile.FullName, Encoding.Default);//必须要指定编码格式，否则中文会乱码，应该可以用UTF-8
                //File.AppendAllText(@"C:\Users\Jiangzm\Desktop\ListString4.txt", String.Format("\r\n/*****************{0}****************\r\n", NextFile.Name));
                while (sr.Peek() > -1)
                {
                    totalNum++;
                    partNum++;
                    readStr = sr.ReadLine();
                    //if (readStr.Length > 70)
                    //{
                    //    continue;
                    //}
                    userInfo = readStr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    try
                    {
                        if (userInfo.Length < 2) continue;
                        else if (userInfo.Length < 3)
                        {
                            if (userInfo[0].Length > 50 || userInfo[1].Length > 50)
                                continue;
                            dt.Rows.Add(0, userInfo[0].Trim(), userInfo[1].Trim(), DBNull.Value);
                        }
                        else if (userInfo.Length < 4)
                        {
                            if (userInfo[0].Length > 50 || userInfo[1].Length > 50 || userInfo[2].Length > 60)
                                continue;
                            dt.Rows.Add(0, userInfo[0].Trim(), userInfo[1].Trim(), userInfo[2].Trim());
                        }
                        else
                        {
                            //list4.Add(readStr);
                            totalError++;
                            partError++;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        totalError++;
                        partError++;
                    }
                    //if (partNum % 100000 == 0) //每读10W条写入到数据库一次
                    //{
                    //    sqlBC.WriteToServer(dt);
                    //    dt.Clear();
                    //}
                }
                //File.AppendAllLines(@"C:\Users\Jiangzm\Desktop\ListString4.txt", list4);
                try
                {
                    sqlBC.WriteToServer(dt);
                    Console.WriteLine("文件" + NextFile.Name + "转换完成。本文件共有：" + partNum + " 条数据，其中失败：" + partError + " 条");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("error:" + ex.Message);
                }
                finally
                {
                    dt.Clear();
                    sr.Close();
                }
            }
            dt.Dispose();
            sqlBC.Close();
            Console.WriteLine("转换完成。文件共有：" + totalNum + " 条数据，其中失败：" + totalError + " 条");
            Console.WriteLine("共耗时：" + (DateTime.Now - time).TotalSeconds.ToString() + " 秒");

            #endregion
        }

        public static void CreateTableDuduniu_User()
        {
            #region Duduniu_User
            /*
                string connectionString = "server=.;database=UserDatabase;uid=sa;pwd=123456;Max Pool Size = 512;";
                DateTime time = DateTime.Now;
                SqlBulkCopy sqlBC = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction);
                sqlBC.DestinationTableName = "Duduniu_User";
                DataTable dt = new DataTable("Duduniu_User");
                dt.Columns.Add("ID",typeof(int));
                dt.Columns.Add("UserName", typeof(string));
                dt.Columns.Add("PassWord", typeof(string));
                dt.Columns.Add("Email", typeof(string));
                DirectoryInfo direct = new DirectoryInfo(@"E:\Jiangzm\WebsiteData\duduniu");
                string[] userInfo;
                string readStr;
                int totalNum = 0;
                int partNum = 0;
                int totalError = 0;
                int partError = 0;
                foreach (FileInfo NextFile in direct.GetFiles())
                {
                    partNum = 0;
                    partError = 0;
                    List<string> listLong = new List<string>();
                    List<string> list4 = new List<string>();
                    Console.WriteLine("正在读取文件：" + NextFile.FullName);
                    StreamReader sr = new StreamReader(NextFile.FullName, Encoding.Default);//必须要指定编码格式，否则中文会乱码，应该可以用UTF-8
                    //File.AppendAllText(@"C:\Users\Jiangzm\Desktop\ListLong.txt", String.Format("\r\n/*****************{0}****************\r\n", NextFile.Name));
                    //File.AppendAllText(@"C:\Users\Jiangzm\Desktop\List4.txt", String.Format("\r\n/*****************{0}****************\r\n", NextFile.Name));
                    while (sr.Peek() > -1)
                    {
                        readStr = sr.ReadLine();
                        if (readStr.Length > 70)
                        {
                            listLong.Add(readStr);
                            continue;
                        }
                        userInfo = readStr.Split(new char[] {  ' ','	' }, StringSplitOptions.RemoveEmptyEntries);
                        try
                        {
                            if (userInfo.Length < 2) continue;
                            else if (userInfo.Length < 3)
                            {
                                if (userInfo[0].Length > 40 || userInfo[1].Length > 50) continue;
                                dt.Rows.Add(0, userInfo[0].Trim(), userInfo[1].Trim(), DBNull.Value);
                            }
                            else if (userInfo.Length < 4)
                            {
                                if (userInfo[0].Length > 40 || userInfo[1].Length > 50 || userInfo[2].Length > 50) continue;
                                dt.Rows.Add(0, userInfo[0].Trim(), userInfo[2].Trim(), userInfo[1].Trim());
                            }
                            else
                            {
                                //list4.Add(readStr);
                                totalError++;
                                partError++;
                            }
                            totalNum++;
                            partNum++;
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                            totalError++;
                            partError++;
                        }

                        //if (partNum % 100000 == 0) //每读10W条写入到数据库一次
                        //{
                        //    sqlBC.WriteToServer(dt);
                        //    dt.Clear();
                        //}
                    }
                    //File.AppendAllLines(@"C:\Users\Jiangzm\Desktop\ListLong.txt", listLong);
                    //File.AppendAllLines(@"C:\Users\Jiangzm\Desktop\List4.txt", list4);
                    try
                    {
                        sqlBC.WriteToServer(dt);
                        Console.WriteLine("文件" + NextFile.Name + "转换完成。本文件共有：" + partNum + " 条数据，其中失败：" + partError + " 条");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("error:" + ex.Message);
                    }
                    finally
                    {
                        dt.Clear();
                        sr.Close();
                    }
                }
                dt.Dispose();
                sqlBC.Close();
                Console.WriteLine("转换完成。文件共有：" + totalNum + " 条数据，其中失败：" + totalError + " 条");
                Console.WriteLine("共耗时：" + (DateTime.Now - time).TotalSeconds.ToString() + " 秒");
                */
            #endregion
        }

        public static void JavascriptWrap(string jsTxt)
        {

        }

        public static void CreateEncodingInfo()
        {
            EncodingInfo[] arrs = Encoding.GetEncodings();
            using (StreamWriter sw = File.AppendText(@"C:\Users\Jiangzm\Desktop\EncodingInfo.txt"))
            {
                foreach (EncodingInfo ei in arrs)
                {
                    sw.WriteLine(ei.Name + "  " + ei.DisplayName + "  " + ei.CodePage.ToString());
                }
            }

        }

        public static void CreateTableZhenai_User()
        {
            string connectionString = "server=Jiangzm-PC;database=UserDatabase;uid=sa;pwd=123456;Max Pool Size = 512;";
            DateTime time = DateTime.Now;
            SqlBulkCopy sqlBC = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction);
            sqlBC.DestinationTableName = "Zhenai_User";
            DataTable dt = new DataTable("Zhenai_User");
            dt.Columns.Add("ID", typeof(Int32));
            dt.Columns.Add("UserName", typeof(string));
            dt.Columns.Add("Password", typeof(string));
            DirectoryInfo direct = new DirectoryInfo(@"E:\Jiangzm\WebsiteData\珍爱网");
            string[] userInfo;
            string readStr;
            int totalNum = 0;
            int partNum = 0;
            int totalError = 0;
            int partError = 0;
            foreach (FileInfo NextFile in direct.GetFiles())
            {
                partNum = 0;
                partError = 0;
                Console.WriteLine("正在读取文件：" + NextFile.FullName);
                StreamReader sr = new StreamReader(NextFile.FullName, Encoding.UTF8);//必须要指定编码格式，否则中文会乱码，应该可以用UTF-8
                while (sr.Peek() > -1)
                {
                    totalNum++;
                    partNum++;
                    readStr = sr.ReadLine();
                    if (IsContainChinese(readStr)) continue;
                    userInfo = readStr.Split(new char[] { '	' }, StringSplitOptions.RemoveEmptyEntries);
                    try
                    {
                        if (userInfo.Length < 1) continue;
                        if (userInfo.Length < 2)
                        {
                            if (userInfo[0].Trim().Length > 50) continue;
                            dt.Rows.Add(0, userInfo[0].Trim(), DBNull.Value);
                        }
                        else if (userInfo.Length < 3)
                        {
                            if (userInfo[0].Trim().Length > 50 || userInfo[1].Trim().Length > 50) continue;
                            dt.Rows.Add(0, userInfo[0].Trim(), userInfo[1].Trim());
                        }
                    }
                    catch (Exception e1)
                    {
                        Console.WriteLine(e1.Message);
                        totalError++;
                        partError++;
                    }
                    //if (partNum % 100000 == 0) //每读10W条写入到数据库一次
                    //{
                    //    sqlBC.WriteToServer(dt);
                    //    dt.Clear();
                    //}
                }
                sqlBC.WriteToServer(dt);
                Console.WriteLine("文件" + NextFile.FullName + "转换完成。本文件共有：" + partNum + " 条数据，其中失败：" + partError + " 条");
                dt.Clear();
                sr.Close();
            }
            dt.Dispose();
            sqlBC.Close();
            Console.WriteLine("转换完成。文件共有：" + totalNum + " 条数据，其中失败：" + totalError + " 条");
            Console.WriteLine("共耗时：" + (DateTime.Now - time).TotalSeconds.ToString() + " 秒");


        }

        #region ChineseChar
        protected bool IsChineseLetter(string input, int index)
        {
            int code = 0;
            int chfrom = Convert.ToInt32("4e00", 16);    //范围（0x4e00～0x9fff）转换成int（chfrom～chend）
            int chend = Convert.ToInt32("9fff", 16);
            if (input != "")
            {
                code = Char.ConvertToUtf32(input, index);    //获得字符串input中指定索引index处字符unicode编码

                if (code >= chfrom && code <= chend)
                {
                    return true;     //当code在中文范围内返回true
                }
                else
                {
                    return false;    //当code不在中文范围内返回false
                }
            }
            return false;
        }
        //方法二：
        public bool IsChina(string CString)
        {
            bool BoolValue = false;
            for (int i = 0; i < CString.Length; i++)
            {
                if (Convert.ToInt32(Convert.ToChar(CString.Substring(i, 1))) < Convert.ToInt32(Convert.ToChar(128)))
                {
                    BoolValue = false;
                }
                else
                {
                    return BoolValue = true;
                }
            }
            return BoolValue;
        }

        //方法三：
        /**/
        /// <summary>
        /// 判断句子中是否含有中文
        /// </summary>
        /// <param >字符串</param>
        public static bool IsContainChinese(string words)
        {
            string TmmP;
            for (int i = 0; i < words.Length; i++)
            {
                TmmP = words.Substring(i, 1);
                byte[] sarr = System.Text.Encoding.GetEncoding("GB18030").GetBytes(TmmP);
                if (sarr.Length == 2)
                {
                    return true;
                }
            }
            return false;
        }

        //方法四：
        //for (int i=0; i<s.length; i++)
        //{
        //Regex rx = new Regex("^[\u4e00-\u9fa5]$");
        //if (rx.IsMatch(s[i]))
        //// 是
        //else
        //// 否
        //}

        /*
         *正解！
         *\u4e00-\u9fa5 汉字的范围。
         *^[\u4e00-\u9fa5]$ 汉字的范围的正则
         */
        //方法五：
        //unicodeencoding   unicodeencoding   =   new   unicodeencoding();
        //byte   []   unicodebytearray   =   unicodeencoding.getbytes(   inputstring   );
        //for(   int   i   =   0;   i   <   unicodebytearray.length;   i++   )
        //{
        //i++;
        ////如果是中文字符那么高位不为0  
        //  if   (   unicodebytearray[i]   !=   0   )
        //{
        //}
        //……

        //方法六：
        /**/
        /// <summary>
        /// 给定一个字符串，判断其是否只包含有汉字
        /// </summary>
        /// <param name="testStr"></param>
        /// <returns></returns>
        public bool IsOnlyContainsChinese(string testStr)
        {
            char[] words = testStr.ToCharArray();
            foreach (char word in words)
            {
                if (IsGBCode(word.ToString()) || IsGBKCode(word.ToString()))  // it is a GB2312 or GBK chinese word
                {
                    continue;
                }
                else
                {
                    return false;
                }
            }
            return true;
        }
        /**/
        /// <summary>
        /// 判断一个word是否为GB2312编码的汉字
        /// </summary>
        /// <param name="word"></param>
        /// <returns></returns>
        private bool IsGBCode(string word)
        {
            byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(word);
            if (bytes.Length <= 1)  // if there is only one byte, it is ASCII code or other code
            {
                return false;
            }
            else
            {
                byte byte1 = bytes[0];
                byte byte2 = bytes[1];
                if (byte1 >= 176 && byte1 <= 247 && byte2 >= 160 && byte2 <= 254)    //判断是否是GB2312
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        /**/
        /// <summary>
        /// 判断一个word是否为GBK编码的汉字
        /// </summary>
        /// <param name="word"></param>
        /// <returns></returns>
        private bool IsGBKCode(string word)
        {
            byte[] bytes = Encoding.GetEncoding("GBK").GetBytes(word.ToString());
            if (bytes.Length <= 1)  // if there is only one byte, it is ASCII code
            {
                return false;
            }
            else
            {
                byte byte1 = bytes[0];
                byte byte2 = bytes[1];
                if (byte1 >= 129 && byte1 <= 254 && byte2 >= 64 && byte2 <= 254)     //判断是否是GBK编码
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        /**/
        /// <summary>
        /// 判断一个word是否为Big5编码的汉字
        /// </summary>
        /// <param name="word"></param>
        /// <returns></returns>
        private bool IsBig5Code(string word)
        {
            byte[] bytes = Encoding.GetEncoding("Big5").GetBytes(word.ToString());
            if (bytes.Length <= 1)  // if there is only one byte, it is ASCII code
            {
                return false;
            }
            else
            {
                byte byte1 = bytes[0];
                byte byte2 = bytes[1];
                if ((byte1 >= 129 && byte1 <= 254) && ((byte2 >= 64 && byte2 <= 126) || (byte2 >= 161 && byte2 <= 254)))  //判断是否是Big5编码
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        public bool GetChinese()
        {
            return true;
        }
        #endregion
    }
}
